<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2020/5/12
 * Time: 15:15
 */

namespace App\Repositories\Eloquent;

use App\ProjectCode;
use Illuminate\Database\Eloquent\Model;
use App\Repositories\Contracts\RepositoryInterface;
use App\Repositories\Exceptions\RepositoryException;

abstract class Repository implements RepositoryInterface
{
    use  BaseRepository;
    use PolicyRepository;

    /**
     * @var App
     */
    private $app;

    /**
     * @var Model|mixed
     */
    protected $model;

    /**
     * Repository constructor.
     * @throws RepositoryException
     */
    public function __construct()
    {
        $this->app = app();
        $this->makeModel();
    }

    /**
     * Specify Model class name
     *
     * @return Model|mixed
     */
    abstract function model();


    /**
     * @return Model|mixed
     * @throws RepositoryException
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function makeModel()
    {
        $model = $this->app->make($this->model());

        if (!$model instanceof Model)
            throw new RepositoryException("Class {$this->model()} must be an instance of Illuminate\\Database\\Eloquent\\Model");

        return $this->model = $model;
    }

    /**
     * @param string $type
     * @return string
     */
    public function getNewCode($type = '')
    {
        $model = ProjectCode::query()
            ->whereDate('created_at', date('Y-m-d'))
            ->where('type', $type)->first();
        if ($model) {
            $model->increment('code');
        } else {
            ProjectCode::query()->where('type', $type)->delete();
            $model = ProjectCode::query()->create(['type' => $type, 'code' => 1]);
        }
        $len = strlen($model['code']) > 4 ? strlen($model['code']) : 4;
        return $type . date('Ymd') . str_pad($model['code'], $len, 0, STR_PAD_LEFT);
    }

    /**
     * @return array
     */
    public function contractTypeOptions()
    {
        return [
            '技术开发' => '技术开发',
            '技术咨询' => '技术咨询',
            '技术转让' => '技术转让',
            '技术服务' => '技术服务',
            '技术许可' => '技术许可',
        ];
    }

    public function updateOrCreate(array $attributes, array $values = [])
    {
        $this->model->newQuery()->updateOrCreate($attributes, $values);
    }

    public function newQuery()
    {
        return $this->model->newQuery();
    }


}
